from django import template

register = template.Library()

# Based on http://svn.navi.cx/misc/trunk/djblets/djblets/datagrid/templatetags/datagrid.py
# Itself heavily based on paginator by insin
# http://www.djangosnippets.org/snippets/73/
@register.inclusion_tag('common/paginator.html', takes_context=True)
def paginator(context, link_type="url", adjacent_pages=5):
    """
    Renders a paginator used for jumping between pages of results.
    """
    page_obj = context['page_obj']
    paginator = context['paginator']
    page_nums = range(max(1, page_obj.number - adjacent_pages),
                      min(paginator.num_pages, page_obj.number + adjacent_pages)
                      + 1)

    return {
        'link_type': link_type,
        'page_obj': page_obj,
        'paginator': paginator,
        'page_numbers': page_nums,
        'show_first': 1 not in page_nums,
        'show_last': paginator.num_pages not in page_nums,
        'extra_query': context.get('extra_query', None),
    }

@register.simple_tag
def page_link(link_type, number, extra_query):
    if link_type == "get":
        eq = ("%s&" % extra_query) if extra_query else ""
        return "?%spage=%s" % (eq, number)
    elif link_type == "url":
        eq = ("?%s" % extra_query) if extra_query else ""
        return "../page%s/%s" % (number, eq)
    else:
        raise template.TemplateSyntaxError("Unknown link_type %s" % link_type)
